#!/bin/bash
# Get the description for a mnemonic.
# Assumes MIBs are in /usr/share/snmp/mibs
# or set $MIBDIRS before calling this script.
# "man snmpcmd" lists all environment variables
# that affect SNMP commands.

#0 for print, 1 for not print
PRINT_TREE="0"

function search_by_snmp()
{
	echo $1 | awk -F '.' '{if (NF > 1) exit 0; exit 1}'
	IS_OID=$?
	if [ $IS_OID -eq 1 ] ; then
		IR_OPT="-IR"
	else
		IR_OPT=""
	fi
	snmptranslate -mAll $IR_OPT -Td $1 2>&1 | awk 'BEGIN\
	{\
		print_tree="'"$PRINT_TREE"'";\
		this_oid="";\
	}\
	{\
		if ( $1 ~ /.*-MIB::.*/) \
		{\
			cnt = split( $1, arr, "::");\
			if ( cnt == 2 ) \
			{\
				this_oid=arr[2];\
			}\
		}\
		if ( ( $1 ~ /::=/ ) && ( $2 ~ /{/ ) && ( $NF ~ /}/ ) ) \
		{\
			if ( this_oid == "" ) this_oid = "'"$1"'";\
			if (print_tree == 1)\
			{\
				printf("::= { %s\n", $3);\
				for ( i = 4; i < NF; i++) \
				{\
					for ( j = 2; j < 2*i ; j++) printf(" ");\
					printf("|\n");\
					for ( j = 2; j < 2*i ; j++) printf(" ");\
					if ( i != (NF-1) ) printf("+-%s\n", $i);\
					if ( i == (NF-1) ) printf("+-%s(%s) }\n", this_oid, $i);\
				}\
			} else {\
				printf("::= { ");\
				for ( i = 3; i < NF; i++ )\
				{\
					cnt = split( $i, arr, "(");\
					if ( cnt != 2 ) \
					{\
						printf(".%s", $i);\
					} else { \
						str = substr( arr[2], 1, length(arr[2]) - 1);\
						printf(".%s", str);\
					}\
				}\
				printf(" }\n");\
				print $0;\
			}\
		} else {\
			if (print_tree != 1) print $0;\
		}\
	}'
	
	return 0
}

function search_by_file()
{
	MIBS_DIR="/usr/share/snmp/mibs"
	
	if [ ! -d $MIBS_DIR ] ;
	then
		echo "Could not open MIB directory : $MIBS_DIR"
		return -1
	fi

	for file in $MIBS_DIR/*
	do
		cat $file | awk 'BEGIN{\
			do_print = 0;\
			ret = 1;\
		}\
		{\
			if ( ($1 ~ "'"$1"'") && ( ($2 ~ ".*-TYPE") || ($2 ~ ".*-GROUP") || ($2 ~ ".*-COMPLIANCE") || ( $2 ~ ".*-IDENTITY") ) && ( do_print == 0 ) )\
			{\
				do_print = 1;\
				ret = 0;\
			}\
			if ( ( $1 ~ "::=" ) && ( $2 ~ "{" ) && ( do_print == 1 ) ) \
			{\
				print $0;\
				do_print = 0;\
			}\
			if ( do_print == 1 ) \
			{\
				print $0;\
			}\
		}\
		END{\
			exit ret;\
		}'
		if [ $? -eq 0 ] ; then
			echo "Found in $file"
			return 0
		fi
	done
	echo "Could not find: $1"
	return 1
}



while [ $# -gt 0 ] ; do
	if [ $1 == "-pt" ] ; then
		PRINT_TREE="1"
		shift
		continue
	fi
	#echo "=============================================================================="
	#echo ""
	#echo "Searching by snmptranslate command ......"
	echo ""
	search_by_snmp $1
	echo ""
	#echo "=============================================================================="
	#echo ""
	#echo "Searching in mib files ......"
	#echo ""
	#search_by_file $1
	#echo ""
	#echo "=============================================================================="
	shift
done

exit 0

